const express = require('express');
const cors = require('cors');
const config = require('../config');
const gameRoutes = require('./routes/gameRoutes');

const app = express();

// CORS 配置
const corsOptions = {
    origin: '*',
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Accept', 'Origin'],
    credentials: false
};

// 应用CORS中间件
app.use(cors(corsOptions));

// 请求体解析
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} from ${req.ip}`);
    next();
});

// 健康检查路由
app.get('/health', (req, res) => {
    console.log('收到健康检查请求');
    res.json({ 
        status: 'ok', 
        timestamp: new Date().toISOString(),
        server: 'nonogram-server',
        version: '1.0.0'
    });
});

// 游戏路由
app.use('/api', gameRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('服务器错误:', err);
    res.status(500).json({
        error: '服务器内部错误',
        message: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
});

const PORT = process.env.PORT || 5000;
//const HOST = '127.0.0.1';
const HOST = '0.0.0.0';
console.log('正在启动服务器...');
console.log(`监听配置: ${HOST}:${PORT}`);

const server = app.listen(PORT, HOST, () => {
    console.log(`
服务器启动成功:
- 时间: ${new Date().toISOString()}
- 地址: http://${HOST}:${PORT}
- 环境: ${process.env.NODE_ENV || 'development'}
- CORS: ${JSON.stringify(corsOptions, null, 2)}
    `);
});

server.on('error', (error) => {
    console.error('服务器错误:', error);
    process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
}); 